<template>
  <view class="goods-props">
    <PropSelect :multiple="true" :data="checkList" title="选择推荐的商品属性" tip="如辣度、甜度等，属性与价格、库存无关" @change="handleSpecChange" @new="handleOpenDialog" />
    <From ref="propForm" :init-data="props" />
    <AddBtn @click.native="handleOpenDialog" />
    <InputDialog ref="InputDialog" title="输入属性值" @submit="name=>handleAddProp(name,[])" />
    <SaveButton @click.native="handleClickSave" />
  </view>
</template>

<script>
import PropSelect from "../../components/public/PropSelect/index.vue";
import SaveButton from "../../components/public/PropSelect/SaveButton.vue";
import From from "./components/Form.vue";
import InputDialog from "@/components/public/Dialog/InputDialog.vue";
import AddBtn from "./components/AddBtn.vue";
import { mapMutations, mapState } from "vuex";
export default {
  components: { PropSelect, SaveButton, From, InputDialog, AddBtn },
  data() {
    return {
      checkList: [
        { name: "甜度", specs: ["甜", "不甜"] },
        { name: "温度", specs: ["热", "常温", "冰"] },
        { name: "辣度", specs: ["辣", "不辣"] }
      ],
      selectProps: []
    };
  },
  watch: {
    selectProps(val, oldVal) {
      // 当长度大于之前的长度时，添加新属性，反之则删除
      let diffProps = this.checkDiff(val, oldVal, "key");
      if (val.length > oldVal.length) {
        let newPropIndex = this.checkList.findIndex(
          v => v.name == diffProps[0]
        );
        this.handleAddProp(diffProps[0], this.checkList[newPropIndex].specs);
      } else {
        this.$refs.propForm.deleteProp(diffProps[0]);
      }
    }
  },
  computed: {
    ...mapState({
      props: state => state.goods.goodsInfo.props
    })
  },
  methods: {
    ...mapMutations({ SET_GOODS_PROPS: "SET_GOODS_PROPS" }),
    handleSpecChange(item) {
      this.selectProps = item.map(v => {
        return {
          key: v.name,
          values: v.specs
        };
      });
    },
    handleClickSave() {
      let formData = this.$refs.propForm.getData();
      if (!formData) return false;
      this.SET_GOODS_PROPS(formData);
      uni.$emit(this.$consts.EMIT_TYPE.SET_PROPS, { props: formData });
      this.$back();
    },
    // 根据key值查找不同的元素
    checkDiff(arr1, arr2, key) {
      let a1 = arr1.map(v => v[key]);
      let a2 = arr2.map(v => v[key]);
      let diffs = a1.concat(a2).filter(function(v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      });
      return diffs;
    },
    handleOpenDialog() {
      this.$refs.InputDialog.open();
    },
    handleAddProp(key, specs = []) {
      this.$refs.propForm.addProp(key, specs);
    }
  }
};
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}
.goods-props {
  padding: 0 $form-item-left;
  padding-top: 60rpx;
  padding-bottom: 150rpx;
}
</style>
